<template>
  <Row>
    <Col span="12">
    <Card :bordered="true" :dis-hover="false" :padding="8">
      <!--表格-->
      <p slot="title" style="height:38px;">
        <Button-group>
          <!--<Button type="ghost" size="large" icon="plus-round"></Button>-->
          <Button type="ghost" size="large" icon="edit" @click="updateRole">修改</Button>
          <Button type="ghost" size="large" icon="trash-b" @click="deleteRole">删除</Button>
        </Button-group>
        <Input v-model="roleQuery.text" @on-enter="searchText" placeholder="查询..." style="max-width: 600px;float: right;">
        <Button slot="append" icon="ios-search" @click="searchText"></Button>
        </Input>
      </p>
      <!--表格-->
      <Table @on-selection-change="selectTable" border :columns="table_show" :data="table_data"></Table>
      <!--分页-->
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
          <Page :current="roleQuery.page" @on-change='changePage' :total="roleQuery.total" simple></Page>
        </div>
      </div>
    </Card>
    </Col>
    <Col span="12">
    <Card :bordered="true" :dis-hover="false" :padding="8">
      <h3 slot="title" style="height:38px;">{{doing}}</h3>
      <!--表单-->
      <Form ref="roleForm" :model="roleForm" :label-width="60" :rules="roleValidate" label-position="right">
        <Form-item label="编号">
          <Input v-model="roleForm.id" placeholder="添加为空" disabled></Input>
        </Form-item>
        <Form-item label="名称" prop="roleName">
          <Input v-model="roleForm.roleName" placeholder="请输入" required @on-enter="roleSubmit('roleForm')"></Input>
        </Form-item>
        <Form-item label="权限" prop="forces">
          <Tree :data="baseTree" show-checkbox multiple ref="tree"></Tree>
        </Form-item>
        <Form-item label="操作">
          <Button type="success" shape="circle" @click.native="roleSubmit('roleForm')" icon="plus">保存</Button>
          <Button type="primary" shape="circle" @click.native="roleReset" icon="arrow-return-left">重置</Button>
        </Form-item>
      </Form>
    </Card>
    </Col>
  </Row>
</template>

<script>
  import roleApi from '@/api/roleApi'
  import forceApi from '@/api/forceApi'

  export default {
    computed: {},
    data() {
      return {
        doing: '添加角色',
        table_show: [{
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '编号',
            width: 80,
            key: 'id',
            align: 'center'
          },
          {
            title: '角色名称',
            align: 'left',
            key: 'role_name'
          },
          {
            title: '操作',
            key: 'action',
            align: 'center',
            fixed: 'right',
            width: 120,
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    shape: 'circle',
                    type: 'ghost',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.show(params.index)
                    }
                  }
                }, '查看权限')
              ]);
            }
          }
        ],
        table_data: [],
        on_select: [],
        roleQuery: {
          text: '',
          page: 1,
          size: 10,
          total: 0
        },
        roleValidate: {
          id: [{
            required: false
          }],
          roleName: [{
            required: true,
            message: '角色名不能为空',
            trigger: 'blur'
          }]
        },
        roleForm: {
          id: '',
          roleName: '',
          forces: []
        },
        force_table: [],
        showMenu: false,
        baseTree: [],
        allForces: [],
      }
    },
    methods: {
      findAllForces() {
        forceApi.tree().then((data) => {
          this.allForces = data
          this.baseTree = []
          for(var i = 0; i < data.length; i++) {
            var icon_root = data[i].force_icon.split('"')
            var temp = {
              title: '<i class="ivu-icon ivu-icon-' + (icon_root && icon_root.length > 2 ? icon_root[1] : '') + '"></i> ' + data[i].force_name,
              id: data[i].id,
              checked: false
            }
            if(data[i].sonForces) {
              temp.children = []
              for(var j = 0; j < data[i].sonForces.length; j++) {
                var icon_son = data[i].sonForces[j].force_icon.split('"')
                var temp_j = {
                  title: '<i class="ivu-icon ivu-icon-' + (icon_son && icon_son.length > 2 ? icon_son[1] : '') + '"></i> ' + data[i].sonForces[j].force_name,
                  id: data[i].sonForces[j].id,
                  checked: false
                }
                temp.children.push(temp_j)
                if(data[i].sonForces[j].sonForces) {
                  temp_j.children = []
                  for(var k = 0; k < data[i].sonForces[j].sonForces.length; k++) {
                    temp_j.children.push({
                      title: data[i].sonForces[j].sonForces[k].force_name,
                      id: data[i].sonForces[j].sonForces[k].id,
                      checked: false
                    })
                  }
                }
              }
            }
            this.baseTree.push(temp)
          }
        }).catch((errMsg) => {

        })
      },
      closeShowMenu() {
        this.showMenu = false
      },
      show(index) {
        var forces = this.table_data[index].forceList
        this.$Modal.info({
          title: '',
          width: 300,
          render: (h) => {
            var baseData = []
            for(var i = 0; i < forces.length; i++) {
              var root = forces[i]
              var icon_root = forces[i].force_icon.toString().split('"')
              var root_node = {
                title: '<i class="ivu-icon ivu-icon-' + (icon_root && icon_root.length > 2 ? icon_root[1] : '') + '"></i> ' + forces[i].force_name,
                expand: true,
                children: []
              }
              baseData.push(root_node)
              if(root.sonForces && root.sonForces.length > 0) {
                for(var j = 0; j < root.sonForces.length; j++) {
                  var menu = root.sonForces[j]
                  var icon_root = root.sonForces[j].force_icon.toString().split('"')
                  var menu_node = {
                    title: '<i class="ivu-icon ivu-icon-' + (icon_root && icon_root.length > 2 ? icon_root[1] : '') + '"></i> ' + root.sonForces[j].force_name,
                    expand: true,
                    children: []
                  }
                  root_node.children.push(menu_node)
                  if(menu.sonForces && menu.sonForces.length > 0) {
                    for(var k = 0; k < menu.sonForces.length; k++) {
                      var force_node = {
                        title: menu.sonForces[k].force_name,
                        expand: true,
                        children: []
                      }
                      menu_node.children.push(force_node)
                    }
                  }
                }
              }
            }
            return h('Tree', {
              props: {
                data: baseData
              }
            })
          },
          okText: '关闭'
        })
      },
      updateRole() {
        var vm = this
        if(vm.on_select.length != 1) {
          this.$Message.error('请选择1项进行操作！')
          return
        }
        vm.roleForm.id = vm.on_select[0].id;
        vm.roleForm.roleName = vm.on_select[0].role_name;
        var temp_forces = vm.on_select[0].forceIds

        for(var i = 0; i < vm.baseTree.length; i++) {
          var flag_root = 0
          vm.baseTree[i].expand = true
          for(var j = 0; j < vm.baseTree[i].children.length; j++) {
            var flag_menu = 0
            vm.baseTree[i].children[j].expand = true
            if(vm.baseTree[i].children[j].children) {
              for(var k = 0; k < vm.baseTree[i].children[j].children.length; k++) {
                if(this.array_contain(temp_forces, vm.baseTree[i].children[j].children[k].id)) {
                  vm.baseTree[i].children[j].children[k].checked = true
                  flag_menu++
                }
              }
            }
            if(vm.baseTree[i].children[j].children && flag_menu == vm.baseTree[i].children[j].children.length) {
              vm.baseTree[i].children[j].checked = true
              flag_root++
            } else if(this.array_contain(temp_forces, vm.baseTree[i].children[j].id)) {
              vm.baseTree[i].children[j].checked = true
              flag_root++
            }
          }
          if(flag_root == vm.baseTree[i].children.length) {
            vm.baseTree[i].checked = true
          }
        }
        vm.doing = '修改角色';
      },
      selectTable(selection) {
        this.on_select = selection
      },
      changePage(index) {
        this.roleQuery.page = index
        this.findRole()
      },
      searchText() {
        this.findRole()
      },
      findRole() {
        var vm = this
        roleApi.findRole(this.roleQuery).then((data) => {
          vm.table_data = data.list
          vm.roleQuery.total = data.totalRow
        }).catch((errMsg) => {

        })
      },
      getMenuNameById(id) {
        var temp = ''
        this.allForces.forEach(function(val, index, arr) {
          if(val.id == id) {
            temp = val.force_name
            return
          }
          if(val.sonForces) {
            for(var i = 0; i < val.sonForces.length; i++) {
              if(val.sonForces[i].id == id) {
                temp = val.sonForces[i].force_name
                return
              }
            }
          }
        })
        return temp
      },
      findInTree(id) {
        var arr = []
        for(var i = 0; i < this.allForces.length; i++) {
          if(this.allForces[i].id == id) {
            // 顶级菜单
            arr.push(id)
            return arr
          }
          var root = this.allForces[i]
          if(root && root.sonForces && root.sonForces.length > 0) {
            for(var j = 0; j < root.sonForces.length; j++) {
              if(root.sonForces[j].id == id) {
                // 二级菜单
                arr.push(root.id)
                arr.push(id)
                return arr
              }
              var menu = root.sonForces[j]
              if(menu && menu.sonForces && menu.sonForces.length > 0) {
                for(var k = 0; k < menu.sonForces.length; k++) {
                  if(menu.sonForces[k].id == id) {
                    // Button菜单
                    arr.push(root.id)
                    arr.push(menu.id)
                    arr.push(id)
                    return arr
                  }
                }
              }
            }
          }
        }
      },
      getSelectTree() {
        var cur = this.$refs.tree.getCheckedNodes()
        var retVal = []
        for(var i = 0; i < cur.length; i++) {
          var arr = this.findInTree(cur[i].id)
          arr = arr.length ? arr : []
          if(arr.length == 1) {
            retVal.push({
              force_root: arr[0]
            })
          } else if(arr.length == 2) {
            var node_state = 0
            for(var j = 0; j < retVal.length; j++) {
              if(retVal[j].force_root == arr[0]) {
                node_state = 1
                if(!retVal[j].force_menus) {
                  retVal[j].force_menus = []
                }
              }
              if(node_state == 1) {
                retVal[j].force_menus.push({
                  force_menu: arr[1]
                })
                continue
              }
            }
            if(node_state == 0) {
              retVal.push({
                force_root: arr[0],
                force_menus: [{
                  force_menu: arr[1]
                }]
              })
              continue
            }
          } else if(arr.length == 3) {
            var node_state = 0
            var menu_node = {}
            for(var j = 0; j < retVal.length; j++) {
              if(retVal[j].force_root == arr[0]) {
                node_state = 1
                menu_node = retVal[j]
                if(!menu_node.force_menus) {
                  menu_node.force_menus = []
                }
              }
              if(node_state == 1) {
                for(var k = 0; k < retVal[j].force_menus.length; k++) {
                  if(retVal[j].force_menus[k].force_menu == arr[1]) {
                    node_state = 2 // 当前节点
                    if(!retVal[j].force_menus[k].force_buttons) {
                      retVal[j].force_menus[k].force_buttons = []
                    }
                    retVal[j].force_menus[k].force_buttons.push(arr[2])
                    continue
                  }
                }
              }
            }
            if(node_state == 1) {
              menu_node.force_menus.push({
                force_menu: arr[1],
                force_buttons: [arr[2]]
              })
              continue
            } else if(node_state == 0) {
              retVal.push({
                force_root: arr[0],
                force_menus: [{
                  force_menu: arr[1],
                  force_buttons: [arr[2]]
                }]
              })
              continue
            }
          }
        }
        return retVal
      },
      roleSubmit(name) {
        var vm = this
        this.$refs[name].validate((valid) => {
          if(valid) {
            this.roleForm.forces = this.getSelectTree()
            this.$Modal.confirm({
              title: '系统提示',
              content: '<p>确认保存这条<br> ' +
                '编号:<font style="color:red">' + (this.roleForm.id ? this.roleForm.id : '暂无') + '</font> <br>' +
                '名称:<font style="color:red">' + this.roleForm.roleName + '</font></p>',
              onOk: () => {
                var msg = this.$Message.loading({
                  content: '正在保存中...',
                  duration: 0
                })
                roleApi.saveRole(this.roleForm).then((data) => {
                  vm.findRole()
                  vm.doing = '添加'
                  vm.roleReset()
                  this.$Message.destroy()
                }).catch((errMsg) => {
                  this.$Message.destroy()
                })
              },
              onCancel: () => {}
            });
          } else {
            this.$Message.error('请认真填写表单!');
          }
        })
      },
      roleReset() {
        var vm = this
        vm.roleForm = {
          id: '',
          roleName: '',
          forces: []
        }
        this.doing = '添加角色'
        for(var i = 0; i < vm.baseTree.length; i++) {
          if(vm.baseTree[i].children) {
            for(var j = 0; j < vm.baseTree[i].children.length; j++) {
              if(vm.baseTree[i].children[j].children) {
                for(var k = 0; k < vm.baseTree[i].children[j].children.length; k++) {
                  vm.baseTree[i].children[j].children[k].checked = false
                }
              }
              vm.baseTree[i].children[j].checked = false
            }
          }
          vm.baseTree[i].checked = false
        }
      },
      deleteRole() {
        var vm = this
        if(vm.on_select.length < 1) {
          this.$Message.error('至少选择1项进行操作！')
          return
        }
        var ids = []
        for(var i = 0; i < vm.on_select.length; i++) {
          ids.push(vm.on_select[i].id)
        }
        this.$Modal.confirm({
          title: '系统提示',
          content: '<p>确认删除<br> ' +
            '编号为<font style="color:red">' + (ids.join(',')) + '</font>的元素么',
          onOk: () => {
            var msg = this.$Message.loading({
              content: '正在删除中...',
              duration: 0
            })
            roleApi.deleteRole(ids.join(',')).then((data) => {
              vm.findRole()
              vm.roleForm = {
                id: '',
                roleName: '',
                forces: []
              }
              vm.doing = '添加角色'
              this.$Message.destroy()
            }).catch((errMsg) => {
              if(errMsg && errMsg !== '') {
                console.log(errMsg)
                this.$Notice.error({
                  title: errMsg,
                  duration: 1
                });
              }
              this.$Message.destroy()
            })
          },
          onCancel: () => {}
        });
      }
    },
    mounted() {
      this.findRole()

      this.findAllForces()
    },
    watch: {}
  }
</script>

<style>

</style>